<template>
  <div id="mapView" class="map-view">
    <!-- 操作面板 -->
    <div class="control-panel">
      <el-card class="control-card">
        <template #header>
          <div class="card-header">
            <h3>事故点上报</h3>
            <p class="subtitle">您可以在地图上标记事故位置并提交信息</p>
          </div>
        </template>
        <el-button type="primary" @click="startAddAccident" :disabled="isDrawing">
          <el-icon><Plus /></el-icon> 标记事故位置
        </el-button>
        <div class="instruction" v-if="isDrawing">
          <el-alert
            title="请在地图上点击添加事故点位置"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </div>

    <!-- 事故点属性表单对话框 -->
    <el-dialog
      v-model="accidentFormVisible"
      title="上报事故信息"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="accidentForm"
        label-width="120px"
        :rules="accidentFormRules"
        ref="accidentFormRef"
      >
        <el-form-item label="事故类型" prop="accident_type">
          <el-select
            v-model="accidentForm.accident_type"
            placeholder="请选择事故类型"
            style="width: 100%"
          >
            <el-option label="追尾" value="追尾"></el-option>
            <el-option label="侧翻" value="侧翻"></el-option>
            <el-option label="碰撞" value="碰撞"></el-option>
            <el-option label="刮蹭" value="刮蹭"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-select
            v-model="accidentForm.severity"
            placeholder="请选择严重程度"
            style="width: 100%"
          >
            <el-option label="轻微" value="轻微"></el-option>
            <el-option label="一般" value="一般"></el-option>
            <el-option label="严重" value="严重"></el-option>
            <el-option label="特别严重" value="特别严重"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="date_time">
          <el-date-picker
            v-model="accidentForm.date_time"
            type="datetime"
            placeholder="请选择发生时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="所属高速公路" prop="highway_code">
          <el-select
            v-model="accidentForm.highway_code"
            placeholder="请选择所属高速公路"
            style="width: 100%"
          >
            <el-option
              v-for="highway in highwayList"
              :key="highway.attributes.OBJECTID"
              :label="highway.attributes.highway_name"
              :value="highway.attributes.highway_code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="位置描述" prop="location_desc">
          <el-input
            v-model="accidentForm.location_desc"
            type="textarea"
            placeholder="请输入位置描述"
            :rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAccidentForm">取消</el-button>
          <el-button type="primary" @click="submitAccidentForm">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提交成功对话框 -->
    <el-dialog v-model="submitSuccessVisible" title="提交成功" width="300px">
      <div class="success-message">
        <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
        <p>您的事故信息已成功提交！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitSuccessVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus, CircleCheckFilled } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'

type AccidentFormType = {
  accident_id: string
  accident_type: string
  severity: string
  date_time: string
  highway_code: string
  location_desc: string
  status: string
}

let view: MapView | null = null
let highwayLayer: FeatureLayer | null = null
let accidentLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let tempGraphic: Graphic | null = null

// 状态变量
const isDrawing = ref(false)
const accidentFormVisible = ref(false)
const submitSuccessVisible = ref(false)
const accidentFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 高速公路列表
let highwayList: Graphic[] = []

// 事故点表单数据
const accidentForm = reactive<AccidentFormType>({
  accident_id: '',
  accident_type: '',
  severity: '',
  date_time: '',
  highway_code: '',
  location_desc: '',
  status: '未处理',
})

// 事故点表单验证规则
const accidentFormRules = {
  accident_type: [{ required: true, message: '请选择事故类型', trigger: 'change' }],
  severity: [{ required: true, message: '请选择严重程度', trigger: 'change' }],
  date_time: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  highway_code: [{ required: true, message: '请选择所属高速公路', trigger: 'change' }],
  location_desc: [{ required: true, message: '请输入位置描述', trigger: 'blur' }],
}

// 开始添加事故点
const startAddAccident = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击添加事故点位置')

  // 开始绘制点
  sketchViewModel.create('point')
}

// 取消事故点表单
const cancelAccidentForm = () => {
  accidentFormVisible.value = false
  resetAccidentForm()

  // 清除临时图形
  if (tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }

  isDrawing.value = false
}

// 重置事故点表单
const resetAccidentForm = () => {
  if (accidentFormRef.value) {
    accidentFormRef.value.resetFields()
  }

  accidentForm.accident_id = ''
  accidentForm.accident_type = ''
  accidentForm.severity = ''
  accidentForm.date_time = ''
  accidentForm.highway_code = ''
  accidentForm.location_desc = ''
  accidentForm.status = '未处理'
}

// 提交事故点表单
const submitAccidentForm = async () => {
  if (!accidentFormRef.value) return

  await accidentFormRef.value.validate(async (valid) => {
    if (valid) {
      // 添加新事故点
      addAccident()
    }
  })
}

// 生成唯一的事故ID
const generateAccidentId = () => {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 1000)
  return `ACC-${timestamp}-${random}`
}

// 添加新事故点
const addAccident = () => {
  if (!tempGraphic || !accidentLayer) return

  // 自动生成事故ID
  accidentForm.accident_id = generateAccidentId()

  // 创建新的事故点图形
  const attributes = {
    accident_id: accidentForm.accident_id,
    accident_type: accidentForm.accident_type,
    severity: accidentForm.severity,
    date_time: accidentForm.date_time,
    highway_code: accidentForm.highway_code,
    location_desc: accidentForm.location_desc,
    status: accidentForm.status,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  accidentLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        accidentFormVisible.value = false
        resetAccidentForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }

        isDrawing.value = false

        // 显示提交成功对话框
        submitSuccessVisible.value = true
      } else {
        ElMessage.error('事故点添加失败')
      }
    })
    .catch((error) => {
      console.error('添加事故点出错:', error)
      ElMessage.error('事故点添加失败')
    })
}

// 加载高速公路列表
const loadHighwayList = async () => {
  if (!highwayLayer) return

  const query = new Query()
  query.where = '1=1'
  query.outFields = ['*']

  try {
    const result = await highwayLayer.queryFeatures(query)
    highwayList = result.features
  } catch (error) {
    console.error('加载高速公路列表失败:', error)
    ElMessage.error('加载高速公路列表失败')
  }
}

// 初始化地图
const initMap = async () => {
  try {
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    view = new MapView({
      container: 'mapView',
      map: map,
      center: [116.404, 39.915], // 北京中心点坐标
      zoom: 10,
    })

    // 创建高速公路图层
    highwayLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/0',
      outFields: ['*'],
      popupTemplate: {
        title: '{highway_name}',
        content: '高速公路名称：{highway_name}',
      },
    })

    // 创建事故点图层
    accidentLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/1',
      outFields: ['*'],
      popupTemplate: {
        title: '事故点信息',
        content: '事故类型：{accident_type}<br>严重程度：{severity}<br>发生时间：{date_time}<br>所属高速公路：{highway_code}<br>位置描述：{location_desc}',
      }
    })

    // 添加图层到地图
    map.add(highwayLayer)
    map.add(accidentLayer)

    // 创建绘图图层和工具
    sketchLayer = new GraphicsLayer()
    map.add(sketchLayer)

    sketchViewModel = new SketchViewModel({
      view: view,
      layer: sketchLayer,
      pointSymbol: new SimpleMarkerSymbol({
        color: [255, 0, 0],
        size: 8,
      }),
    })

    // 监听绘图完成事件
    sketchViewModel.on('create', (event) => {
      if (event.state === 'complete') {
        tempGraphic = event.graphic
        accidentFormVisible.value = true
        isDrawing.value = false
      }
    })

    // 加载高速公路列表
    await loadHighwayList()
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #f5f5f5;
}

.control-panel {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 1;
  width: 300px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.control-card {
  border-radius: 8px;
  background-color: #fff;
  border: none;
}

.card-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.subtitle {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #909399;
}

.instruction {
  margin-top: 15px;
}

.success-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 48px;
  color: #67C23A;
  margin-bottom: 15px;
}
</style>
